<?php
require_once 'models/cms.inc';
require_once 'models/orm.inc';
require_once 'util/translit.inc';


class TCMSCategoryItem extends TCandyItem {
	public function __get($nm){
		$v = parent::__get($nm);
		if ($v)
			return $v;
		
		if ($v === false){
			if ($this->Info)
			switch ($nm){
				case 'Image':
				case 'FullSize':
				case 'Preview':
				case 'Thumbnail':
				case 'SmallThumbnail':
				case 'TinyThumbnail':return $this->Info->$nm;break;			
			}
		}
		
		if (is_null($v) && $nm != 'Info')
			if ($this->Info)
				return $this->Info->$nm;
		return $v;
	}
}


class TCMSCategoryModel extends  TCandyNestedListModel {
/**
 * @var ITransliter[]
 */	
	protected $_ioc_transliter_;
	
/**
 * @var IKeyValueRepository
 */
	protected $_ioc_shop_settings_;
	
/**
 * @var TCMSPageModel
 */	
	protected $_ioc_pages_;
	
	protected $_array_info_properties_ = array('Snippet', 'PageContents', 'Keywords', 'Description', 'Image');
		
	protected function afterConstruct(){
		$this->_conf_classname_ = 'TMSCategory';
	}
	
	protected function beforeSave(TNOrmObject $object){
		$object = parent::beforeSave($object);
		if (!$object->Slug){
			foreach ($this->Transliter as $t)
				if ($t->InputLanguage() == $object->Language){
					$object->Slug = strtolower(trim($t->Transliterate($object->Name)));
					$object->Slug = preg_replace('/-$/','',$object->Slug);
					$object->Slug = str_ireplace(' ','-',$object->Slug);
				}
		}
		if (!$object->Language)
			$object->Language = $this->Application()->Language;
		
		return $object;
	}

	protected function postProcessProperties(){
		parent::postProcessProperties();
		$selection = array();
		$modes = $this->Adapter->Fetch(new TMSShowMode());
		foreach ($modes as $mode)
			$selection[$mode->Id] = (string)$mode;
		$this->propertyMetas['Mode']->SetSelection($selection);
		
		$langsel = array($this->Application()->Language=>'application locale');
		if ($this->ShopSettings)
			if ($langs = $this->ShopSettings->GetValue('Languages')){
			 $langsel = TConvertions::ConvertToArray($langs,array(';','='),array(false,true));
		}
		
		$this->propertyMetas['Language']->SetSelection($langsel);
		$this->propertyMetas['Info']->ReadOnly = true;
		if ($this->Pages){
			foreach ($this->Pages->ClassProperties() as $nm=>$meta)
				if (in_array($nm,$this->InfoProperties))
					$this->propertyMetas[$nm] = $meta;
		}
		unset($this->propertyMetas['Pages']);
	}
	
	protected function preEditItem($id,array $data, $origin){
		return array_diff_key($data, array_flip($this->InfoProperties));
	}	
	
	private function _filter_page_data($d){
		if ($d instanceof TUploadedFile)
			return $d->UploadError() == UPLOAD_ERR_OK;
		return !is_null($d) && ($d !== '');
	}
	
	protected function postEditItem(TCandyItem $item, $origin, array $data = array()){
		$page_data = array_filter(array_intersect_key($data, array_flip($this->InfoProperties)),array($this,"_filter_page_data"));

		if ($this->Pages && !empty($page_data)){
			$info = $item->Info;
				
			$page_data['Language'] = $item->Language;
			$page_data['IsPublished'] = $item->IsPublished;
			$page_data['Mode'] = $item->Mode;
			$page_data['Title'] = $item->Name;
			$page_data['Slug'] = $item->Slug;
				
			if (!$info){
				$info = $this->Pages->CreateItem($page_data);
				$this->EditItem($item->ItemId(), array('Info'=>$info->ItemId()));
			} else $this->Pages->EditItem($info->ItemId(),$page_data);
		}
	}	
	
	public function DeleteObject(TNOrmObject $object){
		$info = $object->Info;
		if ($info)
			$info = $info->Id;
		parent::DeleteObject($object);
		if ($info && $this->Pages)
			$this->Pages->DeleteItem($info);
	}
	
	private function _sort_children($a, $b){
		return $a->OrderNumber - $b->OrderNumber;
	}
	
	public function GetContents($id = null, $direct = true, TListOptions $options = null){
		$result = parent::GetContents($id,$direct,$options);
		if ($direct){
			$temp = array();
			foreach ($result as $c)
				$temp[] = $c;
			usort($temp,array($this,"_sort_children"));
			return new TArrayIterator($temp);
		}
		return $result;
	}
	
	public function WrapObject($object, array &$caller_stack = array()){
		if ($object instanceof TMSCategory)
			return new TCMSCategoryItem($object, $this);
		return parent::WrapObject($object,$caller_stack);
	}
}